// 引入登录、退出登录、获取用户信息的接口
import { login, logout, getInfo } from "@/api/user"
// 获取token,设置token,移除token 函数
import { getToken, setToken, removeToken } from "@/utils/auth"
// 路由模块当中重置路由的方法
import { resetRouter, anyRoutes, asyncRoutes, constantRoutes } from "@/router"
import router from "@/router"
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    routes: [],
    buttons: [],
    // 对比之后 项目中已有的异步路由，与服务器返回的标记信息进行对比，最终展示需要的路由
    resultAsyncRoutes: [],
    resultAllRoutes: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 存储用户信息
  SET_USERINFO: (state, userInfo) => {
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    // 菜单权限标记
    state.routes = userInfo.routes
    // 按钮权限的标记
    state.buttons = userInfo.buttons
    // 用户角色的信息
    state.roles = userInfo.roles
  },
  // 最终计算出来的异步路由
  SET_RESUltASYNCROUTES: (state, asyncRoutes) => {
    // vuex保存当前用户的异步路由
    state.resultAsyncRoutes = asyncRoutes
    // 计算出当前用户的所有路由
    state.resultAllRoutes = constantRoutes.concat(
      state.resultAsyncRoutes,
      anyRoutes
    )
    // 给路由器添加新的路由
    router.addRoutes(state.resultAllRoutes)
  },
}

// 定义一个函数：两个数组进行对比，对比出当前用户到底显示哪些异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
  // 过滤
  return asyncRoutes.filter((item, index) => {
    if (routes.indexOf(item.name) != -1) {
      // 递归 二级路由
      if (item.children && item.children.length) {
        item.children = computedAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

const actions = {
  // 处理登录的业务
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    /* const result = await login({ username: username.trim(), password: password })
    const { data } = result; 
    if(result.code==200000){
      commit("SET_TOKEN", data.token);
      setToken(data.token)
      return Promise.resolve("ok")
    }else {
      return Promise.reject(new Error("failed")); 
    } */
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response
          commit("SET_TOKEN", data.token)
          setToken(data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          // 获取用户信息 routes（返回的标志：不同的用户应该展示哪些菜单的标记）
          // role 用户角色信息 buttons 按钮权限的信息
          const { data } = response
          // vuex存储用户全部的信息
          console.log(data)
          commit("SET_USERINFO", data)
          commit(
            "SET_RESUltASYNCROUTES",
            computedAsyncRoutes(asyncRoutes, data.routes)
          )
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit("RESET_STATE")
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit("RESET_STATE")
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
